package com.zmn.oms.admin.controller.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.common.collect.Lists;
import com.zmn.base.common.data.common.constant.CompanyConst;
import com.zmn.base.common.data.common.dio.company.CompanyDIO;
import com.zmn.base.common.data.common.dro.company.CompanyDRO;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.biz.clue.common.consts.MqConst;
import com.zmn.biz.clue.common.enums.ClueSourceTypeEnum;
import com.zmn.biz.clue.common.enums.LowerStatusEnum;
import com.zmn.biz.clue.common.enums.OrderFailReasonEnum;
import com.zmn.biz.clue.common.model.mq.OrderClueMessageDIO;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.AMISListData;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.gms.common.company.CompanyGridInfoDIO;
import com.zmn.gms.common.company.CompanyGridInfoDRO;
import com.zmn.gms.common.dto.online.grid.GridSpDRO;
import com.zmn.gms.dubbo.interfaces.grid.online.company.CompanyGridListRemoteService;
import com.zmn.gms.dubbo.interfaces.grid.online.order.GridOrderListRemoteService;
import com.zmn.manager.mq.constant.MqTopicConsts;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.manager.redis.RedisManager;
import com.zmn.mcc.common.constant.DpermitConsts;
import com.zmn.mcc.common.dto.permit.SpermitDTO;
import com.zmn.mcc.dubbo.interfaces.dept.DeptListRemoteService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.model.dto.order.OrderServiceCompanyQuery;
import com.zmn.oms.model.dto.order.UnavailableServiceDTO;
import com.zmn.oms.model.dto.order.zmn.CheckManageCompanyDTO;
import com.zmn.oms.model.dto.product.ShowProductDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.order.GridCompanyVO;
import com.zmn.oms.model.vo.work.OrderAssignVO;
import com.zmn.oms.services.interfaces.conf.workturn.biztype.PlatBizTypeService;
import com.zmn.oms.zmn.business.interfaces.clue.OrderClueBService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkAssignBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
//import com.zmn.plat.dubbo.interfaces.plat.biztype.PlatBizTypeListRemoteService;
import com.zmn.sp.common.model.manage.SpServProviderDRO;
import com.zmn.sp.common.model.manage.SpServProviderQuery;
import com.zmn.sp.common.model.rule.ProductAndAddressDIO;
import com.zmn.sp.dubbo.interfaces.manage.SpManageListRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：公司查询
 *
 * @author liuying
 * @date 2018/11/21 15:36
 */
@Slf4j
@Controller
@RequestMapping("/company")
public class CompanyController extends OmsBaseController {

    @Autowired
    private OrderWorkAssignBService orderWorkAssignBService;
    @Autowired
    private ZsOrderWorkBService zsOrderWorkBService;
    @Resource
    private PlatBizTypeService platBizTypeService;

    @Resource
    private OrderClueBService orderClueBService;

    @Resource
    private ZmnMQSender zmnMQSender;
    @Resource
    private RedisManager redisManager;

//    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
//    private PlatBizTypeListRemoteService platBizTypeListRemoteService;
    @DubboReference(version = com.zmn.sp.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    protected SpManageListRemoteService spManageListRemoteService;
    @DubboReference(version = com.zmn.gms.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    GridOrderListRemoteService gridOrderListRemoteService;
    @DubboReference(version = com.zmn.gms.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    CompanyGridListRemoteService companyGridListRemoteService;
    @DubboReference(check = false, version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION)
    DeptListRemoteService deptListRemoteService;

    /**
     * 自动抓取线索开关
     */
    @NacosValue(value = "${enable.save.unavailableService:false}", autoRefreshed = true)
    private boolean enableSaveUnavailableService;
    /**
     * 自动标记测试号码
     */
    @NacosValue(value = "${order.auto.mark.test.telephone:0}", autoRefreshed = true)
    protected List<String> ORDER_AUTO_MARK_TEST_TELEPHONE;

    /**
     * 查询公司列表
     *
     * @param name   公司名称
     * @param type   类型：1服务商，2厂家，3供应商，3大客户
     * @param status 状态：1停用，2启用
     * @return
     */
    @RequestMapping(value = "list/query", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO companyList(@RequestParam(defaultValue = "120") Integer type,
                                 @RequestParam(required = false) Integer status,
                                 @RequestParam(required = false) Integer plat,
                                 @RequestParam(required = false) String name) {

        if (StringUtil.isBlank(name)) {
            return ResultDTO.success(Lists.newArrayList());
        }

        SpermitDTO<Integer> spermitDTO = staffPermitRemoteService.listDpermitByLoginStaff(getCurrentStaff(), DpermitConsts.TYPE_ORGANIZE_SUB, true);

        CompanyDIO baseCompanyDIO = new CompanyDIO();
        baseCompanyDIO.setName(name);
        baseCompanyDIO.setType(type);
        baseCompanyDIO.setStatus(status);
        baseCompanyDIO.setPlat(plat);
        baseCompanyDIO.setCompanyIds(spermitDTO.getItems());
        ResponseDTO<AMISListData<CompanyDRO>> companyResponseDTO = companyListRemoteService.listPageCompanyDROByQuery(baseCompanyDIO);

        if (Objects.nonNull(companyResponseDTO.getData()) && CollectionUtils.isNotEmpty(companyResponseDTO.getData().getItems())) {
            List<CompanyDRO> companyDROList = companyResponseDTO.getData().getItems();
            List<KVDict> dmList = Lists.newArrayListWithCapacity(companyDROList.size());
            companyDROList.forEach(e -> {
                dmList.add(KVDict.<Integer>builder().value(e.getCompanyId()).text(e.getName()).disabled(Objects.equals(e.getStatus(), GlobalConsts.NO)).build());
            });
            return ResultDTO.success(dmList);
        }

        return ResultDTO.success(Lists.newArrayList());
    }

    /**
     * 获取可服务的子公司名称
     *
     * @param query
     * @return
     */
    @RequestMapping(value = "getCompanyName", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO getCompanyByCityId(OrderServiceCompanyQuery query) {
        ShowProductDTO showProductDTO = super.getShowProductIdByProductId(query.getProductId());
        if (Objects.isNull(showProductDTO)) {
            return ResultDTO.success("无公司-未找到产品");
        }

        List<SpServProviderDRO> currentPlatCompany = null;

        // 查询当前平台可服务公司
        ProductAndAddressDIO productAndAddressDIO = new ProductAndAddressDIO();
        productAndAddressDIO.setPlat(query.getPlat());
        productAndAddressDIO.setBizType(query.getBizType());
        productAndAddressDIO.setShowProductId(showProductDTO.getShowProductId());
        productAndAddressDIO.setCountyId(query.getCountyId());
        if (Objects.equals(query.getStreetSource(), OrderConsts.STREET_SOURCE_NONE) ||
                Objects.equals(query.getStreetSource(), OrderConsts.STREET_SOURCE_DEFAULT)) {
            productAndAddressDIO.setStreetId(query.getStreetId());
        } else {
            productAndAddressDIO.setStreetId(0);
        }
        productAndAddressDIO.setLongitude(query.getLongitude());
        productAndAddressDIO.setLatitude(query.getLatitude());

        // F单支持无经纬度可分单，如果不是F单，没有经纬度直接返回，不需要再调接口
        if (!Objects.equals(query.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F) &&
                Objects.isNull(query.getLatitude()) && Objects.isNull(query.getLongitude())){
            currentPlatCompany = Lists.newArrayList();
        } else {
            log.debug("serviceRuleListRemoteService-1#listSpByProductAndAddress[{}]", JSON.toJSONString(productAndAddressDIO));
            ResponseDTO<List<SpServProviderDRO>> listResponseDTO = serviceRuleListRemoteService.listSpByProductAndAddress(productAndAddressDIO);
            log.debug("serviceRuleListRemoteService-1#listSpByProductAndAddress，出参[{}]", listResponseDTO);
            currentPlatCompany = listResponseDTO.getData();
            // 口碑渠道--不分单给家修匠
            if (Objects.equals(ChannelConsts.CHANNEL_ID_KOUBEI, query.getChannelId()) && CollectionUtil.isNotNullOrEmpty(currentPlatCompany)) {
                currentPlatCompany = currentPlatCompany.stream()
                        .filter(e -> !Objects.equals(e.getSubCompanyId(), CompanyConsts.ZMN_JXJ_COMPANY_ID))
                        .collect(Collectors.toList());
            }
        }

        // 如果当前平台是言而有信下单，则加载言而有信虚拟服务商
        if (Objects.equals(query.getPlat(), GlobalConsts.PLAT_MARK_YEYX)) {
            // 言而有信虚拟公司
            OrderWork orderWork = new OrderWork();
            orderWork.setPlatWork(GlobalConsts.PLAT_MARK_YEYX);
            List<OrderAssignVO> yeyxVirtualCompanyVoList = orderWorkAssignBService.listYeyxAssignVirtualCompanyVO(orderWork, null);
            if (CollectionUtils.isNotEmpty(yeyxVirtualCompanyVoList)) {
                OrderAssignVO orderAssignVO = yeyxVirtualCompanyVoList.get(0);
                SpServProviderDRO dro = new SpServProviderDRO();
                dro.setSpId(orderAssignVO.getManageCompanyId());
                dro.setName(orderAssignVO.getManageCompanyName());
                dro.setAssignOrderLevel(orderAssignVO.getSendOrderLevel());
                currentPlatCompany.add(dro);
            }
        }

        // 过滤收款限制的服务公司
        currentPlatCompany = this.listCompanyFilterPaymentLimit(currentPlatCompany, query.getChannelId(), query.getBizType());

        // 获取商品信息
        ProductBaseDRO productBaseDRO = null;
        ProductBaseQuery productDIO = new ProductBaseQuery();
        productDIO.setProductId(showProductDTO.getShowProductId());
        ResponseDTO<List<ProductBaseDRO>> productRemote = productForeignListRemoteService.listBaseDROByQuery(productDIO);
        if (productRemote.isSuccess() && productRemote.getData() != null) {
            productBaseDRO = productRemote.getData().get(0);
        }

        String nonCompanyName = null;

        // 校验平台开通业务类型
        List<Integer> bizTypeList = platBizTypeService.listBizTypeByPlat(query.getPlat());
        if (CollectionUtil.isNullOrEmpty(bizTypeList) || !bizTypeList.contains(query.getBizType())) {
            currentPlatCompany = null;
        }

        // 检查平台是否开通服务分类
        if(Objects.nonNull(productBaseDRO)){
            boolean checkCategory = zsOrderWorkBService.checkOpenCategByPlatAndCateg(query.getPlat(), productBaseDRO.getServCategId(),productBaseDRO.getCategId());
            if (!checkCategory) {
                currentPlatCompany = null;
            }
        }

        if (CollectionUtil.isNullOrEmpty(currentPlatCompany)) {
            nonCompanyName = "暂无服务商可服务";
            this.saveUnavailableService(query, showProductDTO, nonCompanyName);
            return ResultDTO.success(ResultDTO.success(Integer.valueOf(4), "暂无服务商可服务"));
        } else {
            List<OrderAssignVO> orderAssignVOS;
            // 转化成分单对象列表 并获取优先级
            if (Objects.equals(GlobalConsts.PLAT_MARK_ZMN, query.getPlat())) {
                orderAssignVOS = orderWorkAssignBService.listZmnPriorityAssignList(this.convertToOrderAssign(currentPlatCompany), null, null);
            } else if (Objects.equals(GlobalConsts.PLAT_MARK_YEYX, query.getPlat())) {
                orderAssignVOS = orderWorkAssignBService.listYeyxPriorityAssignList(this.convertToOrderAssign(currentPlatCompany), null);
            }else if (Objects.equals(GlobalConsts.PLAT_MARK_CNHB, query.getPlat())) {
                orderAssignVOS = orderWorkAssignBService.listCnhbPriorityAssignList(this.convertToOrderAssign(currentPlatCompany), null);
            }else {
                orderAssignVOS = this.convertToOrderAssign(currentPlatCompany);
            }
            // 显示可服务公司
            if (Objects.equals(orderAssignVOS.size(), 1)) {
                if (Objects.equals(orderAssignVOS.get(0).getManageCompanyId(), 53312)) {
                    this.saveUnavailableService(query, showProductDTO, "无法承接线索");
                    return ResultDTO.success(ResultDTO.success(Integer.valueOf(4), orderAssignVOS.get(0).getManageCompanyName()));
                } else {
                    return ResultDTO.success(ResultDTO.success(Integer.valueOf(1), orderAssignVOS.get(0).getManageCompanyId() + "-" + orderAssignVOS.get(0).getManageCompanyName() + "可服务"));
                }
            }
            // 当前平台有多个公司可以服务
            else {
                return ResultDTO.success(ResultDTO.success(Integer.valueOf(2), "多个服务商可服务"));
            }
        }

        // 查询其他平台可服务公司
        /*List<SpServProviderDRO> otherPlatCompany = Lists.newArrayList();
        List<DictModel> otherPlatList = GlobalConsts.getPlatList().stream().filter(e -> !Objects.equals(e.getKey(), query.getPlat())).collect(Collectors.toList());
        for (DictModel dictModel : otherPlatList) {

            // F单支持无经纬度可分单，如果不是F单，没有经纬度直接返回，不需要再调接口
            if (!Objects.equals(query.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F) &&
                    Objects.isNull(query.getLatitude()) && Objects.isNull(query.getLongitude())){
                continue;
            }

            // 校验平台开通业务类型
            ResponseDTO<List<Integer>> listBizTypeByPlat = platBizTypeListRemoteService.listBizTypeByPlat(dictModel.getKey());
            List<Integer> byPlatData = listBizTypeByPlat.getData();
            if (CollectionUtils.isEmpty(byPlatData)) {
                continue;
            }
            if(!byPlatData.contains(query.getBizType())){
                continue;
            }

            // 检查其他平台是否开通服务分类
            if(Objects.nonNull(productBaseDRO)){
                boolean checkCategory = zsOrderWorkBService.checkOpenCategByPlatAndCateg(dictModel.getKey(),productBaseDRO.getServCategId(),productBaseDRO.getCategId());
                if (!checkCategory) {
                    continue;
                }
            }
            ProductAndAddressDIO otherPlatProductAndAddressDIO = new ProductAndAddressDIO();
            otherPlatProductAndAddressDIO.setPlat(dictModel.getKey());
            otherPlatProductAndAddressDIO.setBizType(query.getBizType());
            otherPlatProductAndAddressDIO.setShowProductId(showProductDTO.getShowProductId());
            otherPlatProductAndAddressDIO.setCountyId(query.getCountyId());
            otherPlatProductAndAddressDIO.setLongitude(query.getLongitude());
            otherPlatProductAndAddressDIO.setLatitude(query.getLatitude());

            log.info("serviceRuleListRemoteService#listSpByProductAndAddress：[{}]", JSON.toJSONString(otherPlatProductAndAddressDIO));
            ResponseDTO<List<SpServProviderDRO>> otherPlatListResponseDTO = serviceRuleListRemoteService.listSpByProductAndAddress(otherPlatProductAndAddressDIO);
            log.info("serviceRuleListRemoteService#listSpByProductAndAddress：[{}]", JSON.toJSONString(otherPlatListResponseDTO));
            List<SpServProviderDRO> otherPlatListResponseDTOData = otherPlatListResponseDTO.getData();
            if (CollectionUtil.isNotNullOrEmpty(otherPlatListResponseDTOData)) {
                // 口碑渠道--不分单给家修匠
                if (Objects.equals(ChannelConsts.CHANNEL_ID_KOUBEI, query.getChannelId()) && CollectionUtil.isNotNullOrEmpty(currentPlatCompany)) {
                    otherPlatListResponseDTOData = otherPlatListResponseDTOData.stream()
                            .filter(e -> !Objects.equals(e.getSubCompanyId(), CompanyConsts.ZMN_JXJ_COMPANY_ID))
                            .collect(Collectors.toList());
                }
                otherPlatCompany.addAll(otherPlatListResponseDTOData);
            }
        }

        // 过滤收款限制的服务公司
        otherPlatCompany = this.listCompanyFilterPaymentLimit(otherPlatCompany, query.getChannelId(), query.getBizType());
        // 过滤库存限制的服务公司
        if (needFilterStock && orderStockDTO != null) {
            otherPlatCompany = this.listCompanyFilterStockLimit(otherPlatCompany, orderStockDTO);
        }
        // 没有平台可以服务
        if (CollectionUtil.isNullOrEmpty(otherPlatCompany)) {
            return ResultDTO.success(ResultDTO.success(Integer.valueOf(0), "当前平台无法服务，其他平台无法服务"));
        }
        // 其他平台可服务
        else {
            *//*Set<String> platNames = Sets.newHashSet();// 可服务平台名称
            List<Integer> manageCompanyIds = otherPlatCompany.stream().map(SpServProviderDRO::getSpId).collect(Collectors.toList());
            List<CompanyDRO> manageCompanies = baseCompanyListRemoteService.listInfoByCompanyIds(manageCompanyIds).getData();
            if (CollectionUtil.isNotNullOrEmpty(manageCompanies)) {
                for (CompanyDRO manageCompany : manageCompanies) {
                    platNames.add(GlobalConsts.getPlatName(manageCompany.getPlat()));
                }
            }
            String showPlatName = platNames.size() > 0 ? StringUtils.join(platNames, "、") : "其他";*//* // 显示可服务的平台名称

            return ResultDTO.success(ResultDTO.success(Integer.valueOf(3), "当前平台无法服务，其他平台可服务"));
        }*/
    }

    /**
     * 获取部门id下所有子部门
     * @param deptIdList
     * @return
     */
    private List<Integer> getCenterDeptIdList(List<Integer> deptIdList) {
        //noinspection rawtypes
        ResponseDTO<List<VtDTO>> listResponseDTO = deptListRemoteService.listSubDeptVtByOrgIdsAndDeptIds(null, deptIdList);
        log.info("查询部门所有子部门出参：【{}】", JSON.toJSONString(listResponseDTO));
        if (!listResponseDTO.isSuccess()) {
            log.info("[{}]查询下级部门失败");
            return Lists.newArrayList(OrderConsts.CUSTOMER_CENTER_DEPT_ID, OrderConsts.ORDER_OPERATE_DEPT_ID, OrderConsts.QUALITY_CONTROL_DEPARTMENT_DEPT_ID_NEW);
        }
        List<VtDTO> list = Optional.ofNullable(listResponseDTO.getData()).orElse(Collections.emptyList());
        List<Integer> resultList = list.stream().map(VtDTO::getValue).collect(Collectors.toList());
        resultList.add(OrderConsts.CUSTOMER_CENTER_DEPT_ID);
        resultList.add(OrderConsts.ORDER_OPERATE_DEPT_ID);
        resultList.add(OrderConsts.QUALITY_CONTROL_DEPARTMENT_DEPT_ID_NEW);

        return resultList;
    }

    /**
     * 不可服务时保存订单信息
     * @param query
     * @param showProductDTO
     * @param reason
     */
    private void saveUnavailableService(OrderServiceCompanyQuery query, ShowProductDTO showProductDTO, String reason) {
        log.info("[{}]自动抓取线索-开始：[{}]", query.getOperatorId(), JSON.toJSONString(query));
        try {
            if (!enableSaveUnavailableService) {
                return;
            }

            // 判断录单人部门  话务、派单、品控、网服等部门员工录单
            log.debug("[{}]自动抓取线索-无法服务操作人部门id:[{}]", query.getOperatorId(), query.getDeptId());
            List<Integer> deptIdList = this.getCenterDeptIdList(Lists.newArrayList(OrderConsts.CUSTOMER_CENTER_DEPT_ID,
                    OrderConsts.ORDER_OPERATE_DEPT_ID, OrderConsts.QUALITY_CONTROL_DEPARTMENT_DEPT_ID_NEW));
            if (!deptIdList.contains(query.getDeptId())) {
                log.debug("[{}]自动抓取线索-录单人部门条件不满足：【{}】", query.getOperatorId(), JSON.toJSONString(deptIdList));
                return;
            }

            // 产品、经纬度、城市、渠道为空不记录
            if (NumberUtil.isNullOrZero(showProductDTO.getShowProductId())
                    || NumberUtil.isNullOrZero(query.getLongitude())
                    || NumberUtil.isNullOrZero(query.getCityId())
                    || NumberUtil.isNullOrZero(query.getChannelId())) {
                log.info("[{}]自动抓取线索-前台产品、经纬度、城市、渠道条件不满足", query.getOperatorId());
                return;
            }

            // 手机号为空
            if (StringUtil.isBlank(query.getTelephone())) {
                log.info("[{}]自动抓取线索-手机号条件不满足：【{}】", query.getOperatorId(), query.getTelephone());
                return;
            }

            // 判断手机号
            if (!StringUtil.isMobile(query.getTelephone())) {
                log.info("[{}]自动抓取线索-手机号条件不满足：【{}】", query.getOperatorId(), query.getTelephone());
                // 判断固定号
                if (!MobileUtil.isFixedPhone(query.getTelephone())) {
                    log.info("[{}]自动抓取线索-固机号条件不满足：【{}】", query.getOperatorId(), query.getTelephone());
                    return;
                }
            }

            // 判断手机号，固定号码，分机号
            if (!StringUtil.isMobile(query.getTelephone()) && !MobileUtil.isFixedPhone(query.getTelephone())) {
                log.info("[{}]自动抓取线索-手机号条件不满足：【{}】", query.getOperatorId(), query.getTelephone());
                return;
            }

            // 测试手机号不记录
            if (ORDER_AUTO_MARK_TEST_TELEPHONE.contains(query.getTelephone())) {
                log.info("[{}]自动抓取线索-测试手机号条件不满足：【{}】", query.getOperatorId(), query.getTelephone());
                return;
            }

            // 测试单不记录
            if (Objects.equals(query.getTest(), com.zmn.consts.GlobalConsts.YES)) {
                log.info("[{}]自动抓取线索-手机号条件不满足：【{}】", query.getOperatorId(), query.getTest());
                return;
            }

            String redisKey = String.format(RedisKeyConsts.ORDER_UNAVAILABLE_SERVICE_KEY, query.getTelephone(), showProductDTO.getShowProductId());
            // 设置redis缓存
            Date end = DateUtil.getDateEnd(DateUtil.getNow());
            long seconds = DateUtil.getTimespan(end.getTime(), DateUtil.UNIT_SECOND);

            Long count = redisManager.incr(redisKey);
            redisManager.expire(redisKey, (int) seconds);
            // 手机号+产品+地址当天记录过不再记录
            if (count > 1) {
                log.info("[{}]自动抓取线索-当天已抓取过", query.getOperatorId());
                return;
            }

            // 将数据同步到线索系统
            orderClueBService.sendOrderOfAutoCaptureToClue(query, reason);

            Date now = new Date();
            UnavailableServiceDTO dto = new UnavailableServiceDTO();
            dto.setPlat(query.getPlat());
            dto.setBizType(query.getBizType());
            dto.setTelephone(query.getTelephone());
            dto.setChannelId(query.getChannelId());
            dto.setChannelName(query.getChannelName());

            dto.setProvinceId(query.getProvinceId());
            dto.setProvinceName(query.getProvinceName());
            dto.setCityId(query.getCityId());
            dto.setCityName(query.getCityName());
            dto.setCountyId(query.getCountyId());
            dto.setStreet(query.getStreet());
            dto.setLongitude(query.getLongitude());
            dto.setLatitude(query.getLatitude());
            dto.setAddress(query.getAddress());

            dto.setServCategId(showProductDTO.getServCategId());
            dto.setServCategName(showProductDTO.getServCategName());
            dto.setShowProductId(showProductDTO.getShowProductId());
            dto.setShowProductName(showProductDTO.getShowProductName());
            dto.setShowCategOneId(showProductDTO.getShowCategOneId());
            dto.setShowCategOneName(showProductDTO.getShowCategOneName());
            dto.setShowCategId(showProductDTO.getShowCategId());
            dto.setShowCategName(showProductDTO.getShowCategName());
            dto.setProductId(showProductDTO.getProductId());
            dto.setProductName(showProductDTO.getProductName());
            dto.setCategOneId(showProductDTO.getCategOneId());
            dto.setCategOneName(showProductDTO.getCategOneName());
            dto.setCategId(showProductDTO.getCategId());
            dto.setCategName(showProductDTO.getCategName());

            dto.setTest(query.getTest());
            dto.setRemark(query.getRemark());
            dto.setReceiveEntranceId(query.getReceiveEntranceId());
            if (StringUtil.isNotBlank(query.getDutyTime())) {
                dto.setDutyTime(DateUtil.dateFormatToDate(query.getDutyTime(), DateUtil.FORMAT_DEFAULT));
            }

            dto.setCreateTime(now);
            dto.setReason(reason);

            String key = String.format("%s_%s_%s", query.getCityId(), dto.getShowProductId(), now.getTime());
            String content = JSON.toJSONString(dto);
            logger.info("自动抓取线索-：key=[{}]，content=[{}]", key, content);
            zmnMQSender.send(MqTopicConsts.ZMN_TOPIC_OMS, MessageQueueTagConsts.ORDER_UNAVAILABLE_SERVICE_TAG, key, content);
        } catch (Exception e) {
            log.error("自动抓取线索失败：[{}]-[{}]", e.getMessage(), query);
            e.printStackTrace();
        }
    }

    /**
     * 过滤收款限制
     * @param list
     * @param channelId
     * @param bizType
     * @return
     */
    private List<SpServProviderDRO> listCompanyFilterPaymentLimit(List<SpServProviderDRO> list, Integer channelId, Integer bizType) {
        if (CollectionUtil.isNullOrEmpty(list)) {
            return list;
        }

        List<Integer> manageCompanyIds = list.stream().map(SpServProviderDRO::getSpId).collect(Collectors.toList());
        List<Integer> listCanServCompanyFilterPaymentLimit = orderWorkAssignBService.listCanServCompanyFilterPaymentLimit(manageCompanyIds, channelId, bizType);
        return list.stream()
                .filter(e -> listCanServCompanyFilterPaymentLimit.contains(e.getSpId()))
                .collect(Collectors.toList());
    }

    /**
     * @param companyId
     * @return
     */
    @RequestMapping(value = "manage/company/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO manageCompanyList(@RequestParam(required = false) Integer companyId,
                                       @RequestParam(required = false) Integer plat,
                                       @RequestParam(required = false) String name) {
        SpServProviderQuery spServProviderQuery = new SpServProviderQuery();
        spServProviderQuery.setSubCompanyIdList(Lists.newArrayList(companyId));
        spServProviderQuery.setName(name);
        spServProviderQuery.setPlat(plat);
        return getManageCompanyList(spServProviderQuery);
    }

    /**
     * @param companyIdList
     * @return
     */
    @RequestMapping(value = "mult/manage/company/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO manageCompanyListByCompanyIds(@RequestParam(required = false) List<Integer> companyIdList,
                                                   @RequestParam(required = false) Integer plat,
                                                   @RequestParam(required = false) String name) {
        SpServProviderQuery spServProviderQuery = new SpServProviderQuery();
        spServProviderQuery.setSubCompanyIdList(companyIdList);
        spServProviderQuery.setPlat(plat);
        spServProviderQuery.setName(name);
        return getManageCompanyList(spServProviderQuery);
    }

    /**
     * 查询服务公司
     *
     * @param spServProviderQuery
     * @return
     */
    private ResultDTO getManageCompanyList(SpServProviderQuery spServProviderQuery) {
        log.info("getManageCompanyList request：{}", spServProviderQuery);
        ResponseDTO<LayuiTableDO<SpServProviderDRO>> responseDTO = spManageListRemoteService.listPageByQuery(spServProviderQuery);
        log.info("getManageCompanyList response：{}", responseDTO);
        LayuiTableDO<SpServProviderDRO> servProviderDROLayuiTableDO = responseDTO.getData();
        if (CollectionUtils.isEmpty(servProviderDROLayuiTableDO.getData())) {
            return ResultDTO.success(Lists.newArrayList());
        }
        List<SpServProviderDRO> servProviderDROList = servProviderDROLayuiTableDO.getData();

        List<KVDict> manageCompanyList = Lists.newArrayList();

        SpermitDTO<Integer> spermitDTO = staffPermitRemoteService.listDpermitByLoginStaff(getCurrentStaff(), DpermitConsts.TYPE_ORGANIZE_SP, false);
        if (CollectionUtils.isEmpty(spermitDTO.getItems())) {
            if (!super.isBranchCompany()) {
                servProviderDROList.forEach(e -> {
                    manageCompanyList.add(KVDict.builder().value(e.getSpId()).text(e.getName()).build());
                });
            }
            return ResultDTO.success(manageCompanyList);
        }

        Set<Integer> collect = null;
        if (CollectionUtils.isNotEmpty(spermitDTO.getItems())) {
            collect = spermitDTO.getItems().stream().collect(Collectors.toSet());
        }
        Set<Integer> finalCollect = collect == null ? null : collect;
        servProviderDROList.forEach(e -> {
            if (finalCollect != null && finalCollect.contains(e.getSpId())) {
                manageCompanyList.add(KVDict.builder().value(e.getSpId()).text(e.getName()).build());
            }
        });

        return ResultDTO.success(manageCompanyList);
    }

    /**
     * 转化成分单对象
     * @param bizAndManageCompanyDROList
     * @return
     */
    private List<OrderAssignVO> convertToOrderAssign(List<SpServProviderDRO> bizAndManageCompanyDROList) {
        List<OrderAssignVO> list = Lists.newArrayList();
        bizAndManageCompanyDROList.forEach(obj -> {
            OrderAssignVO orderAssignVO = new OrderAssignVO();
            orderAssignVO.setCompanyId(obj.getSubCompanyId());
            orderAssignVO.setCompanyName(obj.getSubCompanyName());
            orderAssignVO.setManageCompanyId(obj.getSpId());
            orderAssignVO.setManageCompanyName(obj.getName());
            orderAssignVO.setType(obj.getTwoType());
            orderAssignVO.setSendOrderLevel(obj.getAssignOrderLevel());
            list.add(orderAssignVO);
        });
        return list;
    }

    /**
     * 校验服务商
     * @param dto
     * @return
     */
    @GetMapping("/check")
    @ResponseBody
    public ResultDTO checkCompany(CheckManageCompanyDTO dto) {
        ShowProductDTO showProductDTO = super.getShowProductIdByProductId(dto.getProductId());
        if (Objects.isNull(showProductDTO)) {
            return ResultDTO.success("无公司-未找到产品");
        }
        dto.setShowProductId(showProductDTO.getShowProductId());
        dto.setServCategId(showProductDTO.getServCategId());
        dto.setShowCategId(showProductDTO.getShowCategId());

        return orderWorkAssignBService.checkManageCompany(dto);
    }

    /**
     * 获取平台下所有子公司
     * @param plat
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public ResultDTO listCompany(Integer plat){
        return ResultDTO.success(super.getCompanyListByDept(plat));
    }

    /**
     * 获取行政服务商名称
     * @param query
     * @return
     */
    @RequestMapping(value = "/getGridCompanyName", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO getGridCompanyByCityId(OrderServiceCompanyQuery query) {
        ShowProductDTO showProductDTO = super.getShowProductIdByProductId(query.getProductId());
        if (Objects.isNull(showProductDTO)) {
            return ResultDTO.success(GridCompanyVO.builder().message("未找到产品信息").build());
        }

        log.info("网格-查询网格信息入参：[{}]-[{}]-[{}]-[{}]", query.getLongitude(), query.getLatitude(), showProductDTO.getServCategId(), showProductDTO.getShowCategId());
        ResponseDTO<GridSpDRO> responseDTO = gridOrderListRemoteService.listGridSpByLatLngAndCategoryId(query.getLongitude(),
                query.getLatitude(), String.valueOf(showProductDTO.getServCategId()),
                String.valueOf(showProductDTO.getShowCategId()));
        log.info("网格-查询网格信息出参：[{}]", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess() || Objects.isNull(responseDTO.getData())) {
            this.saveUnavailableService(query, showProductDTO, "暂无网格覆盖");
            return ResultDTO.fail("暂无网格覆盖");
        }

        Integer gridCompanyId = null;
        String gridCompanyName = null;

        GridSpDRO dro = responseDTO.getData();
        CompanyGridInfoDIO dio = new CompanyGridInfoDIO();
        dio.setGridId(dro.getGridId());
        dio.setFirstCategoryId(showProductDTO.getServCategId());
        dio.setSecondCategoryId(showProductDTO.getShowCategOneId());
        dio.setThirdCategoryId(showProductDTO.getShowCategId());
        log.info("网格-查询行政子公司入参：[{}]", JSON.toJSONString(dio));
        ResponseDTO<CompanyGridInfoDRO> gridCompanyResponseDTO = companyGridListRemoteService.getCompanyInfoByGridIdAndCategoryId(dio);
        log.info("网格-查询行政子公司出参：[{}]", JSON.toJSONString(gridCompanyResponseDTO));
        if (gridCompanyResponseDTO.isSuccess() && Objects.nonNull(gridCompanyResponseDTO.getData())) {
            gridCompanyId = gridCompanyResponseDTO.getData().getCompanyId();
            gridCompanyName = gridCompanyResponseDTO.getData().getCompanyName();
        }

        /**
         * 行政服务商规则：修改时，有3个地方
         * 1、下单地址是否划分了网格，没有提示暂无网格覆盖，行政服务商默认塞无法承接线索
         * 2、网格是否有子公司满足，满足看4，不满足看3
         * 3、家修匠的服务商是否满足，满足提示行政服务商，行政子公司为家修匠，不满足提示无法承接线索
         * 4、网格是否有服务商满足，服务商的上级是否是第二步查出的子公司，是提示行政服务商，不是提示行政子公司
         */
        // 如果行政服务商不是空，查询服务商的上级子公司
        if (NumberUtil.isNotNullOrZero(dro.getSpId())) {
            // 获取公司信息
            ResponseDTO<CompanyDRO> companyResponseDTO = companyListRemoteService.getCompanyDROById(dro.getSpId());
            logger.info("网格-获取公司信息出参[{}]", JSON.toJSONString(companyResponseDTO));

            if (NumberUtil.isNullOrZero(gridCompanyId)) {
                if (Objects.equals(companyResponseDTO.getData().getSubCompanyId(), CompanyConsts.ZMN_JXJ_COMPANY_ID)) {
                    return ResultDTO.success(GridCompanyVO.builder().gridCompanyId(CompanyConsts.ZMN_JXJ_COMPANY_ID).message("行政服务商：" + dro.getSpName()).build());
                } else {
                    this.saveUnavailableService(query, showProductDTO, "无法承接线索");
                    return ResultDTO.fail("无法承接线索");
                }
            } else {
                if (Objects.equals(companyResponseDTO.getData().getSubCompanyId(), gridCompanyId)) {
                    return ResultDTO.success(GridCompanyVO.builder().gridCompanyId(gridCompanyId).message("行政服务商：" + dro.getSpName()).build());
                } else {
                    // 查询子公司下信息公司
                    SpServProviderQuery spQuery = new SpServProviderQuery();
                    spQuery.setSubCompanyId(gridCompanyId);
                    spQuery.setThirdType(CompanyConst.COMPANY_TYPE_SERVICE_OCO);
                    spQuery.setStatus(com.zmn.consts.GlobalConsts.YES);
                    ResponseDTO<LayuiTableDO<SpServProviderDRO>> manageCompanyResponseDTO = spManageListRemoteService.listPageByQuery(spQuery);
                    if (manageCompanyResponseDTO.isSuccess() && Objects.nonNull(manageCompanyResponseDTO.getData())
                            && CollectionUtil.isNotNullOrEmpty(manageCompanyResponseDTO.getData().getData())) {
                        return ResultDTO.success(GridCompanyVO.builder().gridCompanyId(gridCompanyId)
                                .message("行政服务商：" + manageCompanyResponseDTO.getData().getData().get(0).getName())
                                .build());
                    }
                    return ResultDTO.success(GridCompanyVO.builder().gridCompanyId(gridCompanyId).message("行政子公司：" + gridCompanyName).build());
                }
            }
        } else {
            if (NumberUtil.isNotNullOrZero(gridCompanyId)) {
                // 查询子公司下信息公司
                SpServProviderQuery spQuery = new SpServProviderQuery();
                spQuery.setSubCompanyId(gridCompanyId);
                spQuery.setThirdType(CompanyConst.COMPANY_TYPE_SERVICE_OCO);
                spQuery.setStatus(com.zmn.consts.GlobalConsts.YES);
                ResponseDTO<LayuiTableDO<SpServProviderDRO>> manageCompanyResponseDTO = spManageListRemoteService.listPageByQuery(spQuery);
                if (manageCompanyResponseDTO.isSuccess() && Objects.nonNull(manageCompanyResponseDTO.getData())
                        && CollectionUtil.isNotNullOrEmpty(manageCompanyResponseDTO.getData().getData())) {
                    return ResultDTO.success(GridCompanyVO.builder().gridCompanyId(gridCompanyId)
                            .message("行政服务商：" + manageCompanyResponseDTO.getData().getData().get(0).getName())
                            .build());
                }
                return ResultDTO.success(GridCompanyVO.builder().gridCompanyId(gridCompanyId).message("行政子公司：" + gridCompanyName).build());
            } else {
                this.saveUnavailableService(query, showProductDTO, "无法承接线索");
                return ResultDTO.fail("无法承接线索");
            }
        }
    }
}
